﻿/*
COPYRIGHT (C) 2011-2013 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using ScrumPilot.Domain;
using ScrumPilot.Domain.BPL;
using ScrumPilot.TFSHelpers;
using user = ScrumPilot.Domain.user;

namespace ScrumPilot.Helpers
{
    public class BaseController : Controller
    {
        #region Properties

        private TFSServices _tfs;

        protected TFSServices TFS
        {
            get
            {
                if (_tfs == null || _tfs.TfsServer == null || !_tfs.TfsServer.HasAuthenticated)
                {
                    if (Session != null && Session["TFSServer"] != null)
                    {
                        _tfs = (TFSServices)Session["TFSServer"];

                    }
                }

                if (_tfs != null && _tfs.TfsServer != null && !_tfs.TfsServer.HasAuthenticated)
                {
                    _tfs.Authenticate();
                }

                return _tfs;
            }
        }

        protected int CurrentUser
        {
            get { return int.Parse(User.Identity.Name); }
        }

        private user _userDB;

        protected user CurrentUserDB
        {
            get { return _userDB ?? (_userDB = (new UserServices(this.TFS) { CurrentUserID = CurrentUser }).CurrentUser); }
        }

        private CultureInfo _ci;

        protected CultureInfo CurrentCulture
        {
            get
            {
                if (_ci == null)
                    if (HttpContext.Request.UserLanguages != null)
                        _ci = new CultureInfo(HttpContext.Request.UserLanguages[0]);
                return _ci;
            }
        }

        private String _tfsRootUrl;
        protected String TfsRootUrl
        {
            get
            {
                if (String.IsNullOrEmpty(_tfsRootUrl))
                {
                    using (var unitOfWork = new UnitOfWork())
                    {
                        var tp = unitOfWork.TfsServerParamsRepository.GetOne();
                        this._tfsRootUrl = "http://" + tp.tfsurl + ":" + tp.tfsport + "/" + tp.tfsdirectory + "/";
                    }
                }
                return this._tfsRootUrl;
            }
        }
        #endregion

        #region pictureHelper

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ShowPhoto16(Int32 id)
        {
            return ShowPhoto(id, 16);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ShowPhoto32(Int32 id)
        {
            return ShowPhoto(id, 32);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ShowPhoto64(Int32 id)
        {
            return ShowPhoto(id, 64);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ShowPhoto96(Int32 id)
        {
            return ShowPhoto(id, 96);
        }

        private ActionResult ShowPhoto(Int32 id, int size)
        {
            //This is my method for getting the image information
            // including the image byte array from the image column in
            // a database.
            var uim = (new UserServices(this.TFS)).GetUserImages(id);
            //As you can see the use is stupid simple.  Just get the image bytes and the
            //  saved content type.  See this is where the contentType comes in real handy.
            Byte[] img = null;
            if (uim != null)
            {
                switch (size)
                {
                    case 16:
                        img = uim.img16;
                        break;
                    case 32:
                        img = uim.img32;
                        break;
                    case 64:
                        img = uim.img64;
                        break;
                    case 96:
                        img = uim.img96;
                        break;
                }
            }
            ImageResult result = uim != null
                                     ? new ImageResult(img, "image/png")
                                     : new ImageResult(
                                           Url.Content(String.Format("~/Content/img/h{0}x{0}.gif", size)), "image/gif");
            return result;
        }

        #endregion

        /// <summary>
        /// Resolve URL from Javascript
        /// </summary>
        /// <param name="listToResolve">URLObject list to resolve</param>
        /// <returns>URLObject with url resolved</returns>
        public JsonResult ResolveUrl(List<UrlResolverModel> listToResolve)
        {
            // todo: update to be compatible with area
            foreach (var model in listToResolve)
            {
                model.Url = !String.IsNullOrEmpty(model.Controller) ?
                    Url.Action(model.Name, model.Controller) :
                    Url.Content("~" + model.Name);
            }
            return Json(listToResolve, JsonRequestBehavior.AllowGet);
        }

        public class UrlResolverModel
        {
            public String Name { get; set; }
            public String Controller { get; set; }
            public String Area { get; set; }
            public String Url { get; set; }
        }

        #region Yammer Helper
        [HttpGet]
        public virtual ActionResult YammerAuthorization()
        {
            // Redirect to the yammer authorize screen to obtain an authorise code
            // ReSharper disable PossibleNullReferenceException
            var root = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.AbsolutePath, String.Empty) + '/';
            // ReSharper restore PossibleNullReferenceException
            var url = new YammerServices().GetLoginAndAuthorizedUrl(root + Url.Action("YammerAuthorizedCode", "Config"));
            return Redirect(url);
        }

        #endregion
    }
}